import { CommonModule, NgFor, NgIf } from '@angular/common';
import { Component, ElementRef, OnInit, ViewChild } from '@angular/core';
import * as echarts from 'echarts';
import { map, of } from 'rxjs';
import { NzButtonModule } from 'ng-zorro-antd/button';
import { NzTabsModule } from 'ng-zorro-antd/tabs';
import { EchartLineComponent, EChartType, SelectTabsComponent, TabType } from "ngx-raw-ui";

@Component({
  selector: 'app-custom-echarts',
  standalone: true,
  imports: [
    CommonModule,
    NgIf,
    NgFor,
    NzButtonModule,
    NzTabsModule,
    EchartLineComponent,

    SelectTabsComponent


  ],

  styleUrl: './custom-echarts.component.scss',
  template: `
    <lib-echart-line [xData]="xData" [yData]="yData" [type]="currentType"/>
    <br/>
  <div id="main" #chartContainer  style="width: 600px;height:400px;"  ></div>

  <lib-select-tabs 
  [tabs]="tabs"
  [selectedTab]="selectedTab"
  (selectedTabChange)="selectedTabChange($event)"
  />



`
})
export class CustomEchartsComponent implements OnInit {



  @ViewChild('chartContainer', { static: true }) chartContainer!: ElementRef;


  xData: number[] = [];
  yData: number[] = [];
  currentType: EChartType = 'line';
  ngOnInit(): void {
    this.loadChartData();
  }

  tabs: TabType[] = [
    { title: 'Line', content: 'line' },
    { title: 'Bar', content: 'bar' },

  ]
  selectedTab: number = 0

  selectedTabChange(i: number) {
    this.selectedTab = i
    console.log('selectedTabChange', i)
  }



  loadChartData() {
    const _data = {
      data: {
        categories: ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'],
        values: [120, 200, 150, 80, 70, 110, 130]
      }
    } as { data: { categories: string[], values: number[] } };

    of(_data).subscribe((data) => {
      this.initChart(data.data);
      this.xData = data.data.values;
      this.yData = data.data.values.map(item => item * 2);
    })
  }

  initChart(data: { categories: string[], values: number[] }) {
    const chartDom = this.chartContainer.nativeElement;
    const myChart = echarts.init(chartDom);
    const option: echarts.EChartsOption = {

      tooltip: {
        trigger: 'axis',
      },
      toolbox: {
        show: true,
        feature: {
          dataView: {
            show: true,
            readOnly: false
          },
          magicType: {
            show: true,
            type: ['line', 'bar']
          },
          restore: {
            show: true
          },
          saveAsImage: {
            show: true
          }
        }
      },

      xAxis: {
        type: 'category',
        data: data.categories,
        name: 'Day'
      },
      yAxis: {
        type: 'value',
        name: 'Value'
      },
      series: [
        {
          name: 'Value',
          data: data.values,
          type: 'line'
        }
      ]
    };
    myChart.setOption(option);
  }

}
